#pragma once

#include "../message_handler.hpp"
#include "../server.hpp"
#include "../../database/mysql_manager.hpp"
#include "../../database/redis_manager.hpp"
#include "../../utils/logger.hpp"
#include <nlohmann/json.hpp>
#include <uuid/uuid.h>
#include <libwebsockets.h>

/**
 * @class AuthHandler
 * @brief 认证消息处理器
 * @details 处理用户登录、注册和登出等认证相关的消息
 */
class AuthHandler : public MessageHandler {
public:
    void handle(struct lws *wsi, const nlohmann::json& data) override {
        // 直接处理数据，不需要额外的action字段
        std::string username = data["username"];
        std::string password = data["password"];

        if (MySQLManager::getInstance().validateUserCredentials(username, password)) {
            auto user = MySQLManager::getInstance().getUserByUsername(username);
            if (user) {
                std::string token = generateToken();
                RedisManager::getInstance().setUserSession(token, user->id);
                RedisManager::getInstance().cacheUserData(*user);
                MySQLManager::getInstance().updateUserLastLogin(user->id);

                Server::getInstance().addSession(wsi, user);

                nlohmann::json response = {
                    {"type", "login_response"},
                    {"data", {
                        {"success", true},
                        {"token", token},
                        {"user", user->toJson()}
                    }}
                };
                Server::getInstance().sendMessage(wsi, response.dump());
            }
        } else {
            nlohmann::json response = {
                {"type", "login_response"},
                {"data", {
                    {"success", false},
                    {"message", "Invalid credentials"}
                }}
            };
            Server::getInstance().sendMessage(wsi, response.dump());
        }
    }

    std::string getType() const override {
        return "auth";
    }

private:
    std::string generateToken() {
        uuid_t uuid;
        uuid_generate(uuid);
        char str[37];
        uuid_unparse(uuid, str);
        return std::string(str);
    }
}; 